// 八卦              000   001  010   011  100   101   110   111
const guaName2 = ['地', '雷', '水', '泽', '山', '火', '风', '天']
export const gua = ['坤', '震', '坎', '兑', '艮', '离', '巽', '乾'].map((name, index) => {
  return {
    name,
    yao: index.toString(2).padStart(3, '0').split('').map(item => item === '1'),
    index,
  }
})

const $64Str = '1、乾为天2、坤为地3、水雷屯4、山水蒙5、水天需6、天水讼7、地水师8、水地比9、风天小畜10、天泽履11、地天泰12、天地否13、天火同人14、火天大有15、地山谦16、雷地豫17、泽雷随18、山风蛊19、地泽临20、风地观21、火雷噬嗑22、山火贲23、山地剥24、地雷复25、天雷无妄26、山天大畜27、山雷颐28、泽风大过29、坎为水30、离为火31、泽山咸32、雷风恒33、天山遁34、雷天大壮35、火地晋36、地火明夷37、风火家人38、火泽睽39、水山蹇40、雷水解41、山泽损42、风雷益43、泽天夬44、天风姤45、泽地萃46、地风升47、泽水困48、水风井49、泽火革50、火风鼎51、震为雷52、艮为山53、风山渐54、雷泽归妹55、雷火丰56、火山旅57、巽为风58、兑为泽59、风水涣60、水泽节61、风泽中孚62、雷山小过63、水火既济64、火水未济'

// export const gua64 = [
//   { name: '乾为天', up: 7, down: 7 },
//   { name: '坤为地', up: 0, down: 0 },
//   { name: '坤为地', up: 0, down: 0 },
// ]

const guaName = { ...Object.fromEntries(gua.map(item => [item.name, item.index])), ...Object.fromEntries(guaName2.map((item, index) => [item, index])) }
// 卦名数组
const guaByNumberArr: Yao[] = Array.from({ length: 64 })

const guaByNameObj: Record<string, Yao> = {}

interface Yao {
  yao: string
  yaoIndex: number
  name: string
  index: number
  up: number
  down: number
}

export const gua64 = $64Str.replace(/\d/g, '').split('、').filter(item => item.length > 0).map((name, index) => {
  const upStr = name.charAt(0)
  const downStr = name.charAt(1)
  const up = guaName[upStr]
  const down = downStr === '为' ? up : guaName[downStr]
  const yao = up.toString(2).padStart(3, '0') + down.toString(2).padStart(3, '0')
  const yaoIndex = Number.parseInt(yao, 2)
  const result = {
    yao,
    yaoIndex,
    name,
    index,
    up,
    down,
  }
  guaByNumberArr[yaoIndex] = result
  guaByNameObj[name] = result
  return result
})

// 根据六爻获取卦信息
export function getGua(gua: string | number) {
  if (typeof gua === 'string') {
    gua = Number.parseInt(gua, 2)
  }
  return guaByNumberArr[gua]
}

export function getCuoGua(gua: string | number) {
  if (typeof gua === 'number') {
    gua = gua.toString(2)
  }
  gua = [...gua].reverse().join('')
  gua = Number.parseInt(gua, 2)
  return guaByNumberArr[gua]
}

export function getHuGua(gua: string | number) {
  if (typeof gua === 'number') {
    gua = gua.toString(2)
  }
  gua = gua.substring(2, 5) + gua.substring(1, 4)
  gua = Number.parseInt(gua, 2)
  return guaByNumberArr[gua]
}

export function yaoBian(gua: string, yaoNum: number) {
  yaoNum = 7 - yaoNum
  const bianYao = gua.slice(yaoNum - 1, yaoNum) === '0' ? '1' : '0'
  return `${gua.slice(0, yaoNum - 1)}${bianYao}${gua.slice(yaoNum)}`
}

export function get8YYaoBian(gua: string) {
  const result: Yao[] = []
  for (let i = 1; i < 6; i++) {
    gua = yaoBian(gua, i)
    result.push(getGua(gua))
  }
  gua = yaoBian(gua, 4)
  result.push(getGua(gua))
  gua = yaoBian(gua, 3)
  gua = yaoBian(gua, 2)
  gua = yaoBian(gua, 1)
  result.push(getGua(gua))
  return result
}
